<script setup>
import {onMounted, onUpdated, ref} from 'vue'

const originalId = 'initial-id' // 初始ID常量
// 定义响应式数据
const dynamicId = ref(originalId)
let counter = 1

// 修改dynamicId的函数
const changeId = () => {
  dynamicId.value = `changed-id-${counter}`
  counter++
}

// 清空ID的函数
const clearId = () => {
  dynamicId.value = null
}

// 还原ID的函数
const resetId = () => {
  dynamicId.value = originalId
  counter = 1 // 重置计数器
}

// 更新按钮HTML显示的函数
const buttonHtml = ref('')
const updateButtonHtml = () => {
  const btn = document.getElementsByClassName('main-btn')
  buttonHtml.value = btn ? btn.item(0).outerHTML : '未找到元素'
}

// 组件挂载和更新时都更新HTML显示
onMounted(updateButtonHtml)
onUpdated(updateButtonHtml)
</script>

<template>
  <h1>v-bind 指令动态绑定示例</h1>

  <div class="container">
    <!-- 显示当前dynamicId的值 -->
    <p>当前dynamicId的值: <strong>{{ dynamicId || '（空）' }}</strong></p>

    <!-- 绑定dynamicId到按钮的id属性 -->
    <button
        v-bind:id="dynamicId"
        @click="changeId"
        class="main-btn"
    >
      点击我修改 dynamicId
    </button>

    <button @click="clearId" class="danger-btn">
      清空ID
    </button>

    <button @click="resetId" class="success-btn">
      还原初始ID
    </button>

    <!-- 显示DOM中实际的id属性变化 -->
    <div class="dom-view">
      <h3>DOM中实际的button元素:</h3>
      <pre>{{ buttonHtml }}</pre>
<!--      <p v-if="!dynamicId" class="warning">⚠️ 注意：当前按钮没有ID属性</p>-->
    </div>
  </div>
</template>

<style scoped>
.container {
  margin: 20px;
  padding: 25px;
  border: 1px solid #eee;
  border-radius: 8px;
  max-width: 650px;
  background-color: #fafafa;
}

.button-group {
  display: flex;
  gap: 15px; /* 增加按钮间距 */
  flex-wrap: wrap;
  margin: 20px 0;
  align-items: center;
}

button {
  padding: 12px 18px 12px 18px; /* 增大按钮内边距 */
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  min-width: 120px; /* 设置最小宽度 */
}

button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.main-btn {
  background-color: #42b983;
  flex-grow: 1; /* 主按钮占据更多空间 */
}

.danger-btn {
  background-color: #ff4757;
}

.success-btn {
  background-color: #2ed573;
}

.dom-view {
  margin-top: 25px;
  padding: 18px;
  background-color: #f5f5f5;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #fff;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #ddd;
  margin-top: 10px;
}

.warning {
  color: #ff6b81;
  margin-top: 12px;
  font-size: 14px;
}

h1 {
  color: #2c3e50;
  margin-bottom: 20px;
}

h3 {
  color: #34495e;
  margin-bottom: 10px;
}
</style>
